<template>
  <div>
    <scroller :show-scrollbar="false"
              class="felx">
      <slider class="slide"
              interval="3000"
              auto-play="true">
        <div v-for="(img, index) in imageList"
             :key="index">
          <image class="slide-image"
                 resize="stretch"
                 :src="img"></image>
        </div>
        <indicator class="indicator"></indicator>
      </slider>

      <div class="bg-white p-3">
        <text class="hint-text">{{hintText}}（万元）</text>
        <text class="fund-text">{{hintFund}}</text>
        <text class="hint-text mb-3">额度大、审批快、费率低，年化费率不超过8%</text>

        <div class="flex-row">
          <text class="btn mr-3"
                @click="goIncrease">增信</text>
          <text class="btn btn-primary"
                @click="onApply">{{applyBtnText}}</text>
        </div>
      </div>

      <vm-title title="贷款管理"
                :show-arrow="false"
                :margin-top="true"
                :hasTopBorder="true"></vm-title>

      <div class="flex-row p-3 bg-white align-center border-bottom"
           @click="onApplyDetail">
        <text class="icon manage-icon">&#xe786;</text>
        <div class="flex">
          <text>{{hintText}}</text>
          <text class="small text-primary">{{hintFund}}万元</text>
        </div>
        <text class="text-primary small p-1 icon">{{manageHintText}} &#xe6a2;</text>
      </div>

      <div class="flex-row p-3 bg-white align-center border-bottom">
        <text class="icon manage-icon">&#xe896;</text>
        <div class="flex">
          <text>还款提示</text>
          <text :class="['small', repayText ? 'text-warning': 'text-muted']">{{repayText || '无需还款'}}</text>
        </div>
        <text class="text-primary small p-1 icon"
              v-if="repayText">查看详情 &#xe6a2;</text>
      </div>

      <vm-title title="贷款流程"
                :show-arrow="false"
                :margin-top="true"
                :hasTopBorder="true"></vm-title>

      <div class="p-3 bg-white">
        <image class="process-image"
               resize="stretch"
               src="bmlocal://assets/credit/credit_process.png"></image>

        <text class="my-3 small text-muted">资料清单</text>

        <text class="small pl-3">{{fileList}}</text>

      </div>

      <text class="p-3 mt-3 text-muted small text-center">望乡农业旗下养鸡供应链金融服务平台</text>
      <text class="mb-3 text-muted text-center">客服电话：0856-5233166</text>

    </scroller>
  </div>
</template>
<script>
import VmTitle from '../../components/vm-title.vue'
import {
  DEFAULT_CLIENT_ID,
  EVENT_GET_FARM,
  STORAGE_FARM,
  STORAGE_CREDIT_RELATED
} from '../../plugins/constant'

const globalEvent = weex.requireModule('globalEvent')

const PROJECT_STATUS_APPROVAL = 100          // 申请中
const PROJECT_STATUS_APPROVAL_REJECT = 101   // 申请被拒
const PROJECT_STATUS_REGISTER = 200          // 审批中
const PROJECT_STATUS_REGISTER_REJECT = 201   // 审批被拒
const PROJECT_STATUS_BEHIND = 300            // 还款中
const PROJECT_STATUS_BEHIND_END = 301        // 贷款已还清

export default {
  components: {
    VmTitle
  },
  props: {},
  data() {
    return {
      farm: {},
      related: {},
      provider: {},
      imageList: [
        'http://vimi8.oss-cn-shenzhen.aliyuncs.com/chick/201957123165836wmd48nn.jpg',
        'http://vimi8.oss-cn-shenzhen.aliyuncs.com/chick/20195712316635mkeml5rk.jpg',
        'http://vimi8.oss-cn-shenzhen.aliyuncs.com/chick/20195712316593f9xyor98.jpg'
      ],
      fileList: '1、经营主体证照\n2、环保证明材料\n3、实际控制人身份证户口册\n4、借款人征信报告\n5、借款人银行流水\n6、与望乡签订的协议\n7、政府相关文件\n8、用电信息',
      manageHintText: '去申请',
      hintText: '最高可贷',
      hintFund: 300,
      applyBtnText: '贷款',
      repayText: '',

      homeBackClickTime: +new Date()
    }
  },
  computed: {
    hasFarm() {
      return this.farm.id && this.farm.id !== DEFAULT_CLIENT_ID
    }
  },
  watch: {},
  eros: {
    beforeBackAppear(params) {
      if (!params) { return }
      if (params.type === 1) {
        this.getCreditRelated()
      }
    }
  },
  created() {
    this.$event.on(EVENT_GET_FARM, res => {
      this.farm = res
      if (res.id === this.farm.id) { return }
      this.init()
    })
    this.getFarmInfo()
    this.androidFinishApp()
  },
  methods: {
    androidFinishApp() {
      globalEvent.addEventListener('homeBack', options => {
        const timeNow = new Date().getTime()
        if (timeNow - this.homeBackClickTime > 2000) {
          this.$notice.toast({ message: '再按一次退出应用' })
          this.homeBackClickTime = timeNow
        } else {
          this.$router.finish()
        }
      })
    },
    getFarmInfo() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      this.init()
    },
    init() {
      this.farm.id && this.getProvider()
    },
    async getProvider() {
      const res = await this.$http({
        method: 'GET',
        name: 'auth.org.provider',
        data: {
          start: 1,
          size: 1,
          orgClass: 'org_credit',
          addressCode: '520600000000'
        }
      })
      if (res && res.data && res.data.length) {
        this.provider = res.data[0]
        this.getCreditRelated()
      }
    },
    async getCreditRelated() {
      const res = await this.$api.getData({
        // server: 'agr_chain',
        // table: 'supplier_related_view',
        server: 'credit',
        table: 'customer_related_view',
        params: {
          index: 1,
          size: 1,
          'service_id.eq': this.provider.orgId,
          'customer_id.eq': this.farm.id
        }
      })
      if (res && res.data && res.data.length) {
        this.related = res.data[0]
        this.setRelated()
        this.$storage.setSync(STORAGE_CREDIT_RELATED, this.related)
      }
    },
    setRelated() {
      const relatedStatus = this.getStatus()
      this.$set(this.related, 'relatedStatus', relatedStatus)
      this.manageHintText = '查看详情'
      this.hintText = relatedStatus.label
      this.hintFund = relatedStatus.funds

      switch (relatedStatus.status) {
        case PROJECT_STATUS_APPROVAL:
          this.hintText = '申请金额'
          this.manageHintText = '修改申请'
          break
        case PROJECT_STATUS_APPROVAL_REJECT:
          this.hintText = '申请未通过'
          this.manageHintText = '修改申请'
          break
        case PROJECT_STATUS_BEHIND_END:
          this.hintText = '已贷金额'
          this.applyBtnText = '增贷'
          break
        case PROJECT_STATUS_BEHIND:
          this.hintText = '已贷金额'
          this.applyBtnText = '续贷'
          // 还款提示
          this.getLevelReview()
          break
        case PROJECT_STATUS_REGISTER:
          this.hintText = '预审金额'
          this.applyBtnText = '续贷'
          break
        case PROJECT_STATUS_REGISTER_REJECT:
          this.hintText = '审核未通过'
          break
        default:
          break
      }
    },
    getStatus() {
      const approvalStatus = +this.related.is_approval
      let funds = +this.related.apply_funds
      if (approvalStatus === 0) {
        return { status: PROJECT_STATUS_APPROVAL, label: '申请中', funds }
      } else if (approvalStatus === 1) {
        // 预审已通过 
        funds = this.related.reply_funds
        const registerStatus = +this.related.approval_register_status
        if (registerStatus === 1) {
          // 已登记
          let label = '已贷金额'
          let status = PROJECT_STATUS_BEHIND
          const behStatus = +this.related.load_beh_status

          if (behStatus === 6) {
            status = PROJECT_STATUS_BEHIND_END
            label = '贷款已还清'
          } else {
            status = PROJECT_STATUS_BEHIND
            switch (behStatus) {
              case 5:
                status = '还款中(损失)'
                break
              case 4:
                status = '还款中(可疑)'
                break
              case 3:
                status = '还款中(次级)'
                break
              case 2:
                status = '还款中(关注)'
                break
              case 1:
                status = '还款中(正常)'
                break
              default:
                break
            }
          }

          return { status, label, funds }
        } else if (registerStatus === 0) {
          // 未审核
          funds = +this.related.approved_funds
          let label = '审核中'
          let status = PROJECT_STATUS_REGISTER
          const taskStatus = this.related.task_status
          if (taskStatus === 0) {
            label = '审核中'
          } else if (taskStatus === 2) {
            label = '分配被拒'
          } else {
            const projectStatus = +this.related.project_status
            if (projectStatus === 1) {
              const isNeedRating = +this.related.is_need_rating
              if (isNeedRating === 1) {
                const ratingStatus = +this.related.rating_status
                label = ratingStatus === 2 ? '审核中' : '评级中'
              } else if (isNeedRating === 2) {
                label = '审核中'
              } else {
                label = '评级中'
              }
            } else {
              label = '调查中'
            }
          }

          return { status, label, funds }
        } else {
          return { status: PROJECT_STATUS_REGISTER_REJECT, label: '审核未通过', funds }
        }
      } else {
        return { status: PROJECT_STATUS_APPROVAL_REJECT, label: '贷款被拒', funds }
      }
      return { status: PROJECT_STATUS_APPROVAL, label: '', funds: 0 }
    },
    async getLevelReview() {
      const res = await this.$api.getData({
        server: 'credit',
        table: 'credit_level_review',
        params: {
          index: 1,
          size: 1,
          'customer_related_id.eq': this.related.customer_related_id
        }
      })
      if (res && res.data && res.data.length) {
        const data = res.data[0]
        const day = data.repay_day
        const type = data.repay_type
        const funds = data.repay_funds

        if (day >= 1 && day <= 31 && type >= 1 && type <= 2) {
          const date = new Date()
          const nowDay = date.getDate()
          const nowMonth = date.getMonth() + 1
          let month = nowDay <= day ? nowMonth : (nowMonth > 11 ? 1 : nowMonth + 1)
          month = type === 2 ? (Math.round(Math.floor((month - 1) / 3)) + 1) * 3 : month
          this.repayText = `${month}月${day}日还款${funds}元`
        }
      }
    },
    goIncrease() {
      if (!this.checkFarm()) { return }
      this.$nav.open({
        name: 'credit.increase',
        params: {
          provider: this.provider,
          related: this.related
        }
      })
    },
    onApply() {
      if (!this.checkFarm()) { return }
      const approvalStatus = +this.related.is_approval
      if (approvalStatus === 0) {
        this.$notice.toast({ message: '正在审批中，请耐心等待！' })
      } else {
        this.$nav.open({
          name: 'credit.apply',
          params: {
            provider: this.provider,
            related: this.related
          }
        })
      }
    },
    onApplyDetail() {
      if (!this.checkFarm()) { return }
      const approvalStatus = +this.related.is_approval
      if (approvalStatus === 2) {
        // 没有申请或申请被拒
        this.$nav.open({
          name: 'credit.apply',
          params: {
            provider: this.provider,
            related: this.related
          }
        })
      } else if (approvalStatus === 0) {
        // 申请中
        this.$nav.open({
          name: 'credit.apply.modify',
          params: {
            provider: this.provider,
            related: this.related
          }
        })
      } else {
        this.$nav.open({
          name: 'credit.apply.detail',
          params: {
            related: this.related,
            provider: this.provider
          }
        })
      }
    },
    checkFarm() {
      if (!this.hasFarm) {
        this.$notice.toast({ message: '请选择创建鸡块' })
        return false
      }
      return true
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}
.p-3 {
  padding: 30px;
}
.p-1 {
  padding: 10px;
}
.pl-3 {
  padding-left: 30px;
}
.mt-3 {
  margin-top: 30px;
}
.mt-2 {
  margin-top: 20px;
}
.mb-3 {
  margin-bottom: 30px;
}
.my-3 {
  margin-top: 30px;
  margin-bottom: 30px;
}
.mr-3 {
  margin-right: 20px;
}
.bg-white {
  background-color: #fff;
}
.text-muted {
  color: #999;
}
.text-warning {
  color: $warning;
}
.text-center {
  text-align: center;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.small {
  font-size: 28px;
}
.text-primary {
  color: $primary;
}
.text-accent {
  color: $accent;
}
.text-center {
  text-align: center;
}
.align-center {
  align-items: center;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color-light;
}

.slide {
  width: 750px;
  height: 300px;
}
.indicator {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 40px;
  background-color: rgba(0, 0, 0, 0);
  item-size: 10px;
  item-color: #eee;
  item-selected-color: $primary;
}
.slide-image {
  width: 750px;
  height: 300px;
}

.fund-text {
  font-size: 70px;
  text-align: center;
  margin-top: 30px;
  margin-bottom: 30px;
}
.hint-text {
  text-align: center;
  font-size: 28px;
  color: #999;
}
.btn {
  flex: 1;
  text-align: center;
  border-width: 1px;
  border-color: $border-color;
  padding: 18px;
  border-radius: 6px;
}
.btn-primary {
  background-color: $primary;
  color: #fff;
  border-color: $primary;
}
.manage-icon {
  font-size: 60px;
  color: $accent;
  margin-right: 30px;
}
.process-image {
  width: 690px;
  height: 260px;
}
</style>
